﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace JsAndSilverLight
{

    //引用浏览器空间
    using System.Windows.Browser;
    using ESRI.ArcGIS.Client;
    using ESRI.ArcGIS.Client.Geometry;
    using ESRI.ArcGIS.Client.Symbols;
    using Skybot.Arcgis.Client.TileLayerExpand;
    using ESRI.ArcGIS.Client.Bing;
    public partial class Page : UserControl
    {
        /// <summary>
        /// 动态图层
        /// </summary>
        private ArcGISDynamicMapServiceLayer california = new ArcGISDynamicMapServiceLayer();




        /// <summary>
        /// Arcgis 全局变量:绘图用
        /// </summary>
        private Draw draw;
        /// <summary>
        /// Arcgis 全局变量:绘图层
        /// </summary>
        private GraphicsLayer gra;

        public Page()
        {
            InitializeComponent();

            string urlStr = Bocom.Silverlight.InitParames.Instance.Parames["Map"];


            //初始化图层
            Map1.Layers.Insert(0,
               new TileLayerBingMapExpand(new Uri("http://192.168.58.90:8456/tiles/r{quadkey}.png?g=49"),
            16, 1) { ID = "UsMap" }
                );

            //加载地图事件
            ((Skybot.Arcgis.Client.TileLayerExpand.TileLayerBingMapExpand)Map1.Layers["UsMap"]).InitializationFailed += ArcGISTiledMapServiceLayer_InitializationFailed;
            //地图加载完成事件
            ((Skybot.Arcgis.Client.TileLayerExpand.TileLayerBingMapExpand)Map1.Layers["UsMap"]).Initialized += (sen, eo) =>
            {
                Dispatcher.BeginInvoke(() =>
                {
                    System.Threading.Thread.Sleep(1000);
                    Envelope envelope = new ESRI.ArcGIS.Client.Geometry.Envelope(new MapPoint(121.2890625, 31.353636941500987).GeographicToWebMercator(),new MapPoint(121.640625, 31.052933985705138).GeographicToWebMercator() );
                    //一定要先移动一下 不然会有错位发生
                    Map1.ZoomTo(envelope);
                    CanvasObj.Visibility = Visibility.Collapsed;

                }
                );


            };
            //改变图像URL
            scalebar.Map = Map1;

            MyNavigation.Map = Map1;

            ///邦定 比例尺
            mapSilder.SetValue(MapSilder.MapProperty, Map1);

            //初始化变量 
            gra = this.Map1.Layers["MyGraphicsLayer"] as GraphicsLayer;
            //设定
            MyMapTip.GraphicsLayer = gra;
            draw = new Draw(this.Map1)
            {
                LineSymbol = new LineSymbol()
                {
                    Color = new SolidColorBrush(Colors.Red),
                    Width = 2
                },
                FillSymbol = new SimpleFillSymbol()
                {
                    BorderBrush = new SolidColorBrush(Colors.Red) { },
                    BorderThickness = 2,
                    Fill = new SolidColorBrush(Colors.Green) { Opacity = 0.5 }
                },
            };
            //注册事件
            draw.DrawComplete += new EventHandler<DrawEventArgs>(draw_DrawComplete);


            #region 初始化鹰眼地图

            MyOverviewMap.Map = Map1;

            MyOverviewMap.Layer = new TileLayerBingMapExpand(new Uri("http://192.168.58.90:8456/tiles/r{quadkey}.png?g=49"),
            16, 1) { ID = "UsMap" };

            #endregion
        }

        int k = 0;
        #region 画图

        /// <summary>
        /// 绘画完成后,显示出来
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void draw_DrawComplete(object sender, DrawEventArgs e)
        {

            #region 地图操作
            switch (CurrentToolType)
            {
                case ToolType.放大:
                    Map1.ZoomTo(e.Geometry);
                    return;

                case ToolType.缩小:
                    {
                        //根据当前视图范围和绘制的框的比例算出新的视图范围大小
                        Envelope currentExtent = Map1.Extent;

                        Envelope zoomBoxExtent = e.Geometry as Envelope;
                        MapPoint zoomBoxCenter = zoomBoxExtent.GetCenter();

                        double whRatioCurrent = currentExtent.Width / currentExtent.Height;
                        double whRatioZoomBox = zoomBoxExtent.Width / zoomBoxExtent.Height;

                        Envelope newEnv = null;

                        if (whRatioZoomBox > whRatioCurrent)
                        {
                            double mapWidthPixels = Map1.Width;
                            double multiplier = currentExtent.Width / zoomBoxExtent.Width;
                            double newWidthMapUnits = currentExtent.Width * multiplier;
                            newEnv = new Envelope(new MapPoint(zoomBoxCenter.X - (newWidthMapUnits / 2), zoomBoxCenter.Y),
                                                           new MapPoint(zoomBoxCenter.X + (newWidthMapUnits / 2), zoomBoxCenter.Y));
                        }
                        else
                        {
                            double mapHeightPixels = Map1.Height;
                            double multiplier = currentExtent.Height / zoomBoxExtent.Height;
                            double newHeightMapUnits = currentExtent.Height * multiplier;
                            newEnv = new Envelope(new MapPoint(zoomBoxCenter.X, zoomBoxCenter.Y - (newHeightMapUnits / 2)),
                                                           new MapPoint(zoomBoxCenter.X, zoomBoxCenter.Y + (newHeightMapUnits / 2)));
                        }

                        if (newEnv != null)
                            Map1.ZoomTo(newEnv);
                    }
                    return;
            }
            #endregion



            #region 给当前图层添加一个气泡提示
            Graphic grap = new Graphic()
            {
                Geometry = e.Geometry,
                Symbol = GetSymbol(e.Geometry, Colors.Blue)

            };
            //发展就是提示的祥细信息
            //定义属性
            grap.Attributes.Add("信息", "当前点" + (k++));
            #endregion


            gra.Graphics.Add(grap);
        }



        /// <summary>
        /// 声明一个工具枚举
        /// </summary>
        public enum ToolType
        {
            放大,
            缩小,
            无
        }

        /// <summary>
        /// 当前的地图工具
        /// </summary>
        private ToolType CurrentToolType
        {
            get;
            set;
        }


        /// <summary>
        /// 工具按钮按下后
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Button button = sender as Button;
            string modetype = button.Content.ToString();
            //设置绘画的方式
            switch (modetype)
            {

                case "点":
                    draw.DrawMode = DrawMode.Point;
                    CurrentToolType = ToolType.无;
                    break;
                case "线":
                    draw.DrawMode = DrawMode.Polyline;
                    CurrentToolType = ToolType.无;

                    break;
                case "面":
                    draw.DrawMode = DrawMode.Polygon;
                    CurrentToolType = ToolType.无;
                    break;
                case "框":
                    draw.DrawMode = DrawMode.Rectangle;
                    CurrentToolType = ToolType.无;
                    break;
                case "任意":
                    draw.DrawMode = DrawMode.Freehand;
                    CurrentToolType = ToolType.无;
                    break;
                case "取消":
                    draw.DrawMode = DrawMode.None;
                    CurrentToolType = ToolType.无;
                    return;
                case "清空":
                    gra.Graphics.Clear();
                    CurrentToolType = ToolType.无;
                    return;


                // 地图操作
                case "放大":
                    CurrentToolType = ToolType.放大;
                    draw.DrawMode = DrawMode.Rectangle;
                    break;

                case "缩小":
                    CurrentToolType = ToolType.缩小;
                    draw.DrawMode = DrawMode.Rectangle;
                    break;

                case "平移":
                    draw.IsEnabled = false;
                    CurrentToolType = ToolType.无;
                    return;

                case "全图":
                    Map1.ZoomTo(Map1.Layers.GetFullExtent());
                    CurrentToolType = ToolType.无;
                    return;




            }
            //激活工具
            draw.IsEnabled = true;
        }



        /// <summary>
        /// 根据几何要素取得对应的渲染符号
        /// </summary>
        /// <param name="ge"></param>
        /// <returns></returns>
        public Symbol GetSymbol(ESRI.ArcGIS.Client.Geometry.Geometry ge, Color color)
        {
            if (ge is MapPoint)
                return new SimpleMarkerSymbol()
                {
                    Color = new SolidColorBrush(color),
                    Size = 10,
                    Style = ESRI.ArcGIS.Client.Symbols.SimpleMarkerSymbol.SimpleMarkerStyle.Circle
                };
            else if (ge is ESRI.ArcGIS.Client.Geometry.Polyline)
                return new LineSymbol() { Color = new SolidColorBrush(color), Width = 3 };
            else if (ge is ESRI.ArcGIS.Client.Geometry.Polygon
                     || ge is ESRI.ArcGIS.Client.Geometry.Envelope)
            {
                Symbol MySm = new SimpleFillSymbol()
                {
                    BorderBrush = new SolidColorBrush(color) { },
                    BorderThickness = 3,
                    Fill = new SolidColorBrush(Colors.Green) { Opacity = 0.5 }
                };
                return MySm;
            }
            return null;
        }


        #endregion



        #region 得到数据
        /// <summary>
        /// 注册脚本块
        /// </summary>

        public void RegScriptBlock()
        {
            //注册一个脚本对像
            //HtmlPage.RegisterScriptableObject("ScriptObj", this);

        }


        /// <summary>
        /// 改变 值
        /// </summary>
        /// <param name="str"></param>
        [ScriptableMember()]
        public void ChangeTextBoxTxt(string str)
        {
            //tt.Text = str;
            // SendUrlGetData();
        }

        #endregion


        //#region 初始化数据
        ///// <summary>
        ///// 去指定的URL得到数据
        ///// </summary>
        //void SendUrlGetData()
        //{
        //    ///得到客户端数据
        //    WcfClicet.Service1Client WcfClient = new JsAndSilverLight.WcfClicet.Service1Client();
        //    WcfClient.GetGpsDataAsync("0002H");
        //    WcfClient.GetGpsDataCompleted += new EventHandler<JsAndSilverLight.WcfClicet.GetGpsDataCompletedEventArgs>(WcfClient_GetGpsDataCompleted);
        //}

        ///// <summary>
        ///// 完成得到数据
        ///// </summary>
        ///// <param name="sender"></param>
        ///// <param name="e"></param>
        //void WcfClient_GetGpsDataCompleted(object sender, JsAndSilverLight.WcfClicet.GetGpsDataCompletedEventArgs e)
        //{
        //    ShowCarsState(e.Result.ToList());
        //}

        ///// <summary>
        ///// 完成后得到数据
        ///// </summary>
        ///// <param name="gpsDatas"></param>
        //void ShowCarsState(List<WcfClicet.GpsData> gpsDatas)
        //{
        //    //tt.Text = "";

        //    //foreach (WcfClicet.GpsData gpsData in gpsDatas)
        //    //{
        //    //    tt.Text += gpsData.内部编号 + ":" + gpsData.状态描述+"\r\n";
        //    //}
        //}

        //#endregion


        /// <summary>
        /// 处理加载事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ArcGISTiledMapServiceLayer_InitializationFailed(object sender, EventArgs e)
        {
            Layer layer = sender as Layer;


            MessageBox.Show(layer.InitializationFailure.Message);

            System.Windows.Browser.HtmlPage.Window.Eval("document.body.innerHTML+='" + layer.InitializationFailure.Message + "';");



        }

        #region 处理图像组件的数据

        private void WorldImageLayer_Initialized(object sender, EventArgs e)
        {

            Map1.ExtentChanged += new EventHandler<ExtentEventArgs>(Map1_ExtentChange);

            Map1.ExtentChanging += new EventHandler<ExtentEventArgs>(Map1_ExtentChange);

        }


        // 没错，把两个事件绑定到同一个handler即可。再看看Map1_ExtentChange中的代码： 
        private void Map1_ExtentChange(object sender, ExtentEventArgs e)
        {

            TBextent.Text = string.Format("地图范围：\nMinX:{0}\nMinY:{1}\nMaxX:{2}\nMaxY:{3}",

            e.NewExtent.XMin, e.NewExtent.YMin, e.NewExtent.XMax, e.NewExtent.YMax);


            TBzoomdurationvalue.Text = string.Format("当前值：{0}.{1}秒", Map1.ZoomDuration.Seconds, Map1.ZoomDuration.Milliseconds);

            TBpandurationvalue.Text = string.Format("当前值：{0}.{1}秒", Map1.PanDuration.Seconds, Map1.PanDuration.Milliseconds);



        }



        /// <summary>
        /// Mouse 事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Map1_MouseMove(object sender, MouseEventArgs e)
        {

            if (Map1.Extent != null)
            {

                System.Windows.Point screenPnt = e.GetPosition(Map1);

                TBscreencoords.Text = string.Format("屏幕坐标：\nX：{0}，Y：{1}", screenPnt.X, screenPnt.Y);



                MapPoint mapPnt = Map1.ScreenToMap(screenPnt);

                TBmapcoords.Text = string.Format("地图坐标：\nX：{0}\nY：{1}", Math.Round(mapPnt.WebMercatorToGeographic().X, 4), Math.Round(mapPnt.Y, 4));


                TBzoomdurationvalue.Text = string.Format("当前值：{0}.{1}秒", Map1.ZoomDuration.Seconds, Map1.ZoomDuration.Milliseconds);

                TBpandurationvalue.Text = string.Format("当前值：{0}.{1}秒", Map1.PanDuration.Seconds, Map1.PanDuration.Milliseconds);


            }

        }

        /// <summary>
        /// Map里的动画效果。
        ///当地图放大和平移时都可以看到平滑的效果，这归功于Silverlight的动画功能。Map在封装完动画效果后，给了我们两个属性来对它们进行设置：PanDuration和ZoomDuration，用于设置这两个动作持续的时间。它们都是TimeSpan类型的变量，合理的设置可以带来良好的用户体验。看看这部分的布局：
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void slideranimation_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {

            Slider s = sender as Slider;

            if (s.Name == "sliderzoomanimation")
            {

                Map1.ZoomDuration = new TimeSpan(0, 0, Convert.ToInt32(sliderzoomanimation.Value));

                TBzoomdurationvalue.Text = string.Format("当前值：{0}秒", Convert.ToInt32(sliderzoomanimation.Value));

            }

            else
            {

                Map1.PanDuration = new TimeSpan(0, 0, Convert.ToInt32(sliderpananimation.Value));

                TBpandurationvalue.Text = string.Format("当前值：{0}秒", Convert.ToInt32(sliderpananimation.Value));

            }

        }


        #endregion

        /// <summary>
        /// 地图加载进度处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Map1_Progress(object sender, ProgressEventArgs e)
        {
            MyProgressBar.Value = e.Progress;
            ProgressValueTextBlock.Text = e.Progress.ToString() + "%";
        }



    }
}
